package com.oneraku.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oneraku.service.domain.*;
import com.oneraku.service.exceptions.InfoException;
import com.oneraku.service.service.*;
import com.oneraku.service.utils.*;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: hui.ren@huberbuy.com
 * @Date: 2020/4/6 13:20
 */
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private IUserAdminService adminService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IMerchantCategoryService merchantCategoryService;
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private IWorkOrderCommentService commentService;
    @Autowired
    private IAgentSeckillService agentSeckillService;
    @Autowired
    private IOperatorService operatorService;
    @Autowired
    private IAgentStepInfoService stepInfoService;
    @Autowired
    private IAddressInfoService addressInfoService;
    @Autowired
    private IAbroadVirtualAddressService virtualAddressService;
    private String getRandomPassword(int len){
        Random rand = new Random();
        StringBuilder sb = new StringBuilder();
        String strAll = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 0; i < len; i++) {
            int f = (int) (Math.random()*62);
            sb.append(strAll.charAt(f));
        }
        return sb.toString();
    }
    @Override
    public R login(UserAdmin admin) {
        if(StringUtils.isEmpty(admin.getUsername()) || StringUtils.isEmpty(admin.getPassword())){
            throw new InfoException("请输入用户名或密码");
        }
        UserAdmin userAdmin =  adminService.getOne(Wrappers.<UserAdmin>lambdaQuery().eq(UserAdmin::getUsername,admin.getUsername()),false);
        if(null == userAdmin){
            throw new InfoException("用户名或密码不正确");
        }
        if (!Bcrypt.checkpw(admin.getPassword(),userAdmin.getPassword())) {
            throw new InfoException("用户名或密码不匹配");
        }
        String token = TokenUtils.getToken(userAdmin.getId());
        adminService.update(Wrappers.<UserAdmin>lambdaUpdate().set(UserAdmin::getToken,token).eq(UserAdmin::getId,userAdmin.getId()));
        userAdmin.setPassword(null);
        userAdmin.setToken(token);
        userAdmin.setTokenExpired(System.currentTimeMillis() + 1000 * 60 * 20);

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        operator.setUname(userAdmin.getName()+"["+userAdmin.getUsername()+"]");
        operator.setName("管理员登录");
        operatorService.save(operator);

        return R.ok(userAdmin);
    }
    @Override
    public R userinfo() {
        return R.ok(RequestConsoleUserUtils.getUser());
    }
    @Override
    public R logout() {
        adminService.update(Wrappers.<UserAdmin>lambdaUpdate().set(UserAdmin::getToken,"").eq(UserAdmin::getId,RequestConsoleUserUtils.getUser().getId()));

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName("管理员退出");
        operatorService.save(operator);
        return R.ok("success");
    }
    @Override
    public R selfEdit(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(userAdmin.getName())){
            throw new InfoException("姓名不能为空");
        }
        adminService.update(Wrappers.<UserAdmin>lambdaUpdate()
                .set(UserAdmin::getName,userAdmin.getName())
                .eq(UserAdmin::getId,consoleBean.getId())
        );
        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName("修改自己的信息");
        operatorService.save(operator);
        return R.ok("success");
    }
    @Override
    public R mangerList(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(consoleBean.getManager()){
            IPage page = adminService.page(userAdmin.page(),Wrappers.<UserAdmin>lambdaQuery().eq(UserAdmin::getManager,false));
            return R.okPage(page);
        } else {
            return R.okEmptyPage();
        }
    }
    @Override
    public R mangerAdd(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(!consoleBean.getManager()){
            throw new InfoException("权限不足");
        } else {
            if(StringUtils.isEmpty(userAdmin.getUsername()) || StringUtils.isEmpty(userAdmin.getName())){
                throw new InfoException("账号或姓名不能为空！");
            }
            if(adminService.count(Wrappers.<UserAdmin>lambdaQuery().eq(UserAdmin::getUsername,userAdmin.getUsername()))>0){
                throw new InfoException("账号已存在");
            }
            String password = "oneraku1234";
//            String password = getRandomPassword(8);
            userAdmin.setId(null);
            userAdmin.setPassword(Bcrypt.hashpw(password,Bcrypt.gensalt()));
            userAdmin.setCreateTime(null);
            userAdmin.setTokenExpired(null);
            userAdmin.setToken(null);
            userAdmin.setManager(false);
            adminService.save(userAdmin);

            Operator operator = new Operator();
            operator.setIp(RequestIpUtils.getIp());
            ConsoleBean logUser = RequestConsoleUserUtils.getUser();
            operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
            operator.setName(String.format("添加管理员【%s】",userAdmin.getUsername()));
            operatorService.save(operator);
            return R.ok(password);
        }
    }
    @Override
    public R mangerDel(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(!consoleBean.getManager()){
            throw new InfoException("权限不足");
        } else {
            if(StringUtils.isEmpty(userAdmin.getId())){
                throw new InfoException("缺少参数！");
            }
            UserAdmin userAdmin1 = adminService.getById(userAdmin.getId());
            if(userAdmin1 == null || userAdmin1.getManager()){
                throw new InfoException("删除失败！");
            }

            Operator operator = new Operator();
            operator.setIp(RequestIpUtils.getIp());
            ConsoleBean logUser = RequestConsoleUserUtils.getUser();
            operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
            operator.setName(String.format("删除管理员【%s】",userAdmin1.getUsername()));
            operatorService.save(operator);

            return R.ok(adminService.removeById(userAdmin.getId()));
        }
    }
    @Override
    public R mangerEdit(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(!consoleBean.getManager()){
            throw new InfoException("权限不足");
        } else {
            if(StringUtils.isEmpty(userAdmin.getUsername()) || StringUtils.isEmpty(userAdmin.getName())){
                throw new InfoException("账号或姓名不能为空！");
            }
            if(adminService.count(Wrappers.<UserAdmin>lambdaQuery().eq(UserAdmin::getUsername,userAdmin.getUsername()).ne(UserAdmin::getId,userAdmin.getId()))>0){
                throw new InfoException("账号已存在");
            }
            UserAdmin userAdmin1 = adminService.getById(userAdmin.getId());
            if(userAdmin1 == null || userAdmin1.getManager()){
                throw new InfoException("编辑失败！");
            }

            Operator operator = new Operator();
            operator.setIp(RequestIpUtils.getIp());
            ConsoleBean logUser = RequestConsoleUserUtils.getUser();
            operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
            operator.setName(String.format("编辑【%s】管理员信息",userAdmin1.getUsername()));
            operatorService.save(operator);

            return R.ok(adminService.update(Wrappers.<UserAdmin>lambdaUpdate()
                    .set(UserAdmin::getUsername,userAdmin.getUsername())
                    .set(UserAdmin::getName,userAdmin.getName())
                    .eq(UserAdmin::getId,userAdmin.getId())
            ));
        }
    }
    @Override
    public R resetPassword(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(userAdmin.getPassword())){
            throw new InfoException("新密码不能为空");
        }
        if(StringUtils.isEmpty(userAdmin.getOldPassword())){
            throw new InfoException("旧密码不能为空");
        }
        UserAdmin userAdmin1 = adminService.getById(consoleBean.getId());
        if(userAdmin1 == null){
            throw new InfoException("更新异常");
        }
        if(!Bcrypt.checkpw(userAdmin.getOldPassword(),userAdmin1.getPassword())){
            throw new InfoException("旧密码不正确");
        }

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName(String.format("重置【%s】密码",userAdmin1.getUsername()));
        operatorService.save(operator);

        return R.ok(adminService.update(Wrappers.<UserAdmin>lambdaUpdate().set(UserAdmin::getPassword,Bcrypt.hashpw(userAdmin.getPassword(),Bcrypt.gensalt())).eq(UserAdmin::getId,consoleBean.getId())));
    }
    @Override
    public R initPassword(UserAdmin userAdmin) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(!consoleBean.getManager()){
            throw new InfoException("权限不足");
        }
        UserAdmin userAdmin1 = adminService.getById(userAdmin.getId());
        if(null == userAdmin1){
            throw new InfoException("未找到相关的用户");
        }

        String password = getRandomPassword(8);
        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName(String.format("初始化【%s】密码",userAdmin1.getUsername()));
        operatorService.save(operator);

        adminService.update(Wrappers.<UserAdmin>lambdaUpdate().set(UserAdmin::getPassword,Bcrypt.hashpw(password,Bcrypt.gensalt())).eq(UserAdmin::getId,userAdmin1.getId()));
        return R.ok(password);
    }
    @Override
    public R merchantList(Merchant merchant) {
        RequestConsoleUserUtils.getUser();
        return R.okPage(merchantService.page(merchant.page(),Wrappers.emptyWrapper()));
    }
    @Override
    public R merchantAdd(Merchant merchant) {
        RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(merchant.getTitle())
                || StringUtils.isEmpty(merchant.getImg())
                || StringUtils.isEmpty(merchant.getUrl())
                || StringUtils.isEmpty(merchant.getCategory())
        ){
            throw new InfoException("海外商家标题，图片，跳转地址，分类不能为空");
        }
        merchant.setId(null);
        merchant.setCreateTime(null);
        merchantService.save(merchant);

        int categoryName = merchantCategoryService.count(Wrappers.<MerchantCategory>lambdaQuery().eq(MerchantCategory::getCategory,merchant.getCategory()));
        if(categoryName <= 0){
            MerchantCategory category =   new MerchantCategory();
            category.setSeq(1);
            category.setCategory(merchant.getCategory());
            merchantCategoryService.save(category);
        }

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName("新增海外商家["+merchant.getTitle()+"]");
        operatorService.save(operator);

        return R.ok(merchant.getId());
    }
    @Override
    public R merchantDel(Merchant merchant) {
        RequestConsoleUserUtils.getUser();
        Merchant merchant1 = merchantService.getById(merchant.getId());
        if(merchant1!=null){
            merchantService.removeById(merchant);
            Set<String> categorys = merchantService.list(Wrappers.<Merchant>lambdaQuery().select(Merchant::getCategory)).stream().map(item->item.getCategory()).collect(Collectors.toSet());
            if(categorys.size() >0 ){
                merchantCategoryService.remove(Wrappers.<MerchantCategory>lambdaQuery().notIn(MerchantCategory::getCategory,categorys));
            } else {
                merchantCategoryService.removeByIds(merchantCategoryService.list());
            }
            Operator operator = new Operator();
            operator.setIp(RequestIpUtils.getIp());
            ConsoleBean logUser = RequestConsoleUserUtils.getUser();
            operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
            operator.setName("删除海外商家["+merchant1.getTitle()+"]");
            operatorService.save(operator);
        }
        return R.ok("success");
    }
    @Override
    public R merchantEdit(Merchant merchant) {
        RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(merchant.getTitle())
                || StringUtils.isEmpty(merchant.getImg())
                || StringUtils.isEmpty(merchant.getUrl())
                || StringUtils.isEmpty(merchant.getCategory())
        ){
            throw new InfoException("海外商家标题，图片，跳转地址，分类不能为空");
        }

        int categoryName = merchantCategoryService.count(Wrappers.<MerchantCategory>lambdaQuery().eq(MerchantCategory::getCategory,merchant.getCategory()));
        if(categoryName <= 0){
            MerchantCategory category =   new MerchantCategory();
            category.setSeq(1);
            category.setCategory(merchant.getCategory());
            merchantCategoryService.save(category);
        }

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName("编辑海外商家["+merchant.getTitle()+"]");
        operatorService.save(operator);

        return R.ok(merchantService.updateById(merchant));
    }
    @Override
    public R workOrderList(WorkOrder workOrder) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        IPage<WorkOrder> page;
        if(consoleBean.getManager()){
            page = workOrderService.page(workOrder.page(),Wrappers.<WorkOrder>lambdaQuery()
                    .like(!StringUtils.isEmpty(workOrder.getName()),WorkOrder::getName,workOrder.getName())
                    .eq(!StringUtils.isEmpty(workOrder.getCategory()),WorkOrder::getCategory,workOrder.getCategory())
                    .eq(!StringUtils.isEmpty(workOrder.getId()),WorkOrder::getId,workOrder.getId())
                    .orderByDesc(WorkOrder::getCreateTime));
        } else {
            page = workOrderService.page(workOrder.page(),Wrappers.<WorkOrder>lambdaQuery()
                    .like(!StringUtils.isEmpty(workOrder.getName()),WorkOrder::getName,workOrder.getName())
                    .eq(!StringUtils.isEmpty(workOrder.getCategory()),WorkOrder::getCategory,workOrder.getCategory())
                    .eq(WorkOrder::getHandler,consoleBean.getId())
                    .eq(!StringUtils.isEmpty(workOrder.getId()),WorkOrder::getId,workOrder.getId())
                    .orderByDesc(WorkOrder::getCreateTime));
        }
        if(page.getRecords().size() > 0){
            Set<String> adminIds = page.getRecords().stream().map(item->item.getHandler()).filter(item->!StringUtils.isEmpty(item)).collect(Collectors.toSet());
            Set<String> orderIds = page.getRecords().stream().map(item->item.getId()).collect(Collectors.toSet());
            QueryWrapper<WorkOrderComment> wrapper = new QueryWrapper<WorkOrderComment>();
            wrapper.select("work_order_id,count(*) as count");
            wrapper.in("work_order_id",orderIds);
            wrapper.eq("`sread`",0);
            wrapper.eq("type","usr");
            wrapper.groupBy("work_order_id");
            List<WorkOrderComment> workOrderComments = commentService.list(wrapper);
            Map<String,Integer> workOrderCommentsMap = new HashMap<String,Integer>();
            workOrderComments.forEach(item->{
                workOrderCommentsMap.put(item.getWorkOrderId(),item.getCount());
            });
            if(adminIds.size()>0){
                List<UserAdmin> adminList = adminService.list(Wrappers.<UserAdmin>lambdaQuery().select(UserAdmin::getName,UserAdmin::getId).in(UserAdmin::getId,adminIds));
                Map<String,String> nameMap = new HashMap<String,String>();
                adminList.forEach(item->{
                    nameMap.put(item.getId(),item.getName());
                });
                page = page.convert(item->{
                    String name = nameMap.get(item.getHandler());
                    if(!StringUtils.isEmpty(name)){
                        item.setHandlerName(name);
                    } else {
                        item.setHandlerName("");
                    }
                    Integer orderNotice = workOrderCommentsMap.get(item.getId());
                    if(null == orderNotice){
                        item.setNotice(0);
                    } else {
                        item.setNotice(orderNotice);
                    }
                    return item;
                });
            } else {
                page = page.convert(item->{
                    Integer orderNotice = workOrderCommentsMap.get(item.getId());
                    if(null == orderNotice){
                        item.setNotice(0);
                    } else {
                        item.setNotice(orderNotice);
                    }
                    return item;
                });
            }
        }
        return R.okPage(page);
    }
    @Override
    public R mangerSelect() {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(consoleBean.getManager()){
            return R.ok(adminService.list(Wrappers.<UserAdmin>lambdaQuery().select(UserAdmin::getName,UserAdmin::getId)));
        } else {
            UserAdmin userAdmin = new UserAdmin();
            userAdmin.setId(consoleBean.getId());
            userAdmin.setName(consoleBean.getName());
            return R.ok(Collections.singletonList(userAdmin));
        }
    }
    @Override
    public R workOrderAssign(WorkOrder workOrder) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(!consoleBean.getManager()){
            throw new InfoException("权限不足");
        } else {
            if(StringUtils.isEmpty(workOrder.getHandler())){
                throw new InfoException("分配标识未知");
            }
            UserAdmin userAdmin1 = adminService.getById(workOrder.getHandler());
            if(null == userAdmin1){
                throw new InfoException("分配标识未知");
            }
            WorkOrder order = workOrderService.getById(workOrder.getId());
            if(order == null){
                throw new InfoException("工单不存在");
            }
            Operator operator = new Operator();
            operator.setIp(RequestIpUtils.getIp());
            ConsoleBean logUser = RequestConsoleUserUtils.getUser();
            operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
            operator.setName("分配工单["+order.getName()+"]给["+userAdmin1.getName()+"]");
            operatorService.save(operator);

            return R.ok(workOrderService.update(Wrappers.<WorkOrder>lambdaUpdate().set(WorkOrder::getHandler,userAdmin1.getId()).eq(WorkOrder::getId,order.getId())));
        }
    }
    @Override
    public R workOrderComments(WorkOrderComment comment) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(comment.getWorkOrderId())){
            throw new InfoException("缺少参数");
        }
        WorkOrder workOrder = workOrderService.getById(comment.getWorkOrderId());
        if(null == workOrder){
            throw new InfoException("未找到相关的工单信息");
        }
        if(!consoleBean.getManager() && consoleBean.getId().equals(workOrder.getHandler())){
            throw new InfoException("无权查看该工单详情");
        }
        commentService.update(Wrappers.<WorkOrderComment>lambdaUpdate().set(WorkOrderComment::getSread,true).eq(WorkOrderComment::getWorkOrderId,comment.getWorkOrderId()).eq(WorkOrderComment::getType,"usr"));
        return R.okPage(commentService.page(comment.page(),Wrappers.<WorkOrderComment>lambdaQuery().eq(WorkOrderComment::getWorkOrderId,comment.getWorkOrderId()).orderByDesc(WorkOrderComment::getCreateTime)));
    }
    @Override
    public R addWorkOrderComments(WorkOrderComment comment) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(comment.getWorkOrderId())){
            throw new InfoException("缺少参数");
        }
        WorkOrder workOrder = workOrderService.getById(comment.getWorkOrderId());
        if(null == workOrder){
            throw new InfoException("未找到相关的工单信息");
        }
        if(!consoleBean.getManager() && consoleBean.getId().equals(workOrder.getHandler())){
            throw new InfoException("无权查看该工单详情");
        }
        comment.setSid(consoleBean.getId());
        comment.setType("sys");
        commentService.save(comment);

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName("新增["+workOrder.getName()+"]工单回复处理");
        operatorService.save(operator);

        return R.ok(comment.getId());
    }
    @Override
    public R agentBuyList(AgentSeckill agentSeckill) {
        RequestConsoleUserUtils.getUser();
        IPage<AgentSeckill> page= agentSeckillService.page(agentSeckill.page(),
                Wrappers.<AgentSeckill>lambdaQuery()
                .eq(AgentSeckill::getType,agentSeckill.getType())
                .eq(!StringUtils.isEmpty(agentSeckill.getStatus()),AgentSeckill::getStatus,agentSeckill.getStatus())
                .like(!StringUtils.isEmpty(agentSeckill.getName()),AgentSeckill::getName,agentSeckill.getName())
                .orderByDesc(AgentSeckill::getCreateTime)

        );
        Set<String> uids = page.getRecords().stream().map(item->item.getCreator()).collect(Collectors.toSet());
        if(uids.size()>0){
          List<AddressInfo> addressInfos =  addressInfoService.list(Wrappers.<AddressInfo>lambdaQuery().eq(AddressInfo::getDefaults,1).in(AddressInfo::getUid,uids)).stream().collect(Collectors.toList());
          Map<String, List<AddressInfo>> addressMap =   addressInfos.stream().collect(Collectors.groupingBy(AddressInfo::getUid));


          List<AbroadVirtualAddress> addressVInfos =  virtualAddressService.list(Wrappers.<AbroadVirtualAddress>lambdaQuery().in(AbroadVirtualAddress::getUid,uids)).stream().collect(Collectors.toList());
          Map<String, List<AbroadVirtualAddress>> addressVMap =   addressVInfos.stream().collect(Collectors.groupingBy(AbroadVirtualAddress::getUid));
            page =   page.convert(item->{
                String uid = item.getCreator();
                List<AddressInfo> addressInfoList = addressMap.get(uid);
                if(addressInfoList!=null && addressInfoList.size()>0){
                    AddressInfo addressInfo = addressInfoList.get(0);
                    item.setAddress(addressInfo.getCountry()+addressInfo.getProvince()+addressInfo.getCity()+addressInfo.getDistrict());
                }
                List<AbroadVirtualAddress>  virtualAddress = addressVMap.get(uid);
                if(virtualAddress!=null && virtualAddress.size()>0){
                    AbroadVirtualAddress addressInfo2 = virtualAddress.get(0);
                    item.setVisualAddr(addressInfo2.getName());
                }
                return item;
            });
        }





        return R.okPage(page);
    }
    @Override
    public R agentBuyDeal(AgentSeckill agentSeckill) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        if(StringUtils.isEmpty(agentSeckill.getId())){
            throw new InfoException("更新标识未知");
        }

        AgentSeckill agentSeckill1 = agentSeckillService.getById(agentSeckill.getId());
        if(null == agentSeckill1){
            throw new InfoException("更新标识未知");
        }
        AgentStepInfo agentStepInfo = stepInfoService.getOne(Wrappers.
                <AgentStepInfo>lambdaQuery()
                .eq(AgentStepInfo::getAgentId,agentSeckill.getId())
                .eq(AgentStepInfo::getAgentStep,String.valueOf(agentSeckill.getStatus())));
        if(null == agentStepInfo){
            AgentStepInfo stepInfo = new AgentStepInfo();
            stepInfo.setInfo(agentSeckill.getInfo());
            stepInfo.setAgentId(agentSeckill.getId());
            stepInfo.setAgentStep(agentSeckill.getStatus());
            stepInfoService.save(agentStepInfo);
        } else {
            stepInfoService.update(Wrappers.
                    <AgentStepInfo>lambdaUpdate()
                    .set(AgentStepInfo::getInfo,agentSeckill.getInfo())
                    .eq(AgentStepInfo::getId,agentStepInfo.getId())
            );
        }

        Operator operator = new Operator();
        operator.setIp(RequestIpUtils.getIp());
        ConsoleBean logUser = RequestConsoleUserUtils.getUser();
        operator.setUname(logUser.getName()+"["+logUser.getUsername()+"]");
        operator.setName("处理["+agentSeckill1.getName()+"]["+StepEnum.getMessage(agentSeckill.getStatus())+"]");
        operatorService.save(operator);

        agentSeckillService.update(Wrappers.<AgentSeckill>lambdaUpdate().set(AgentSeckill::getStatus,agentSeckill.getStatus()).set(AgentSeckill::getStep,agentSeckill.getStatus()).eq(AgentSeckill::getId,agentSeckill1.getId()));
        return R.ok(agentSeckill.getStep());
    }
    @Override
    public R operators(Operator operator) {
        ConsoleBean consoleBean = RequestConsoleUserUtils.getUser();
        IPage<Operator> page= operatorService.page(operator.page(),
                Wrappers.<Operator>lambdaQuery()
                        .orderByDesc(Operator::getCreateTime)

        );
        return R.okPage(page);
    }
    @Override
    public R agentBuySteps(String id) {
        List<AgentStepInfo> agentStepInfos = stepInfoService.list(Wrappers.<AgentStepInfo>lambdaQuery().eq(AgentStepInfo::getAgentId,id));
        agentStepInfos = agentStepInfos.stream().map(item->{
            item.setAgentStepName(StepEnum.getName(Integer.valueOf(item.getAgentStep())));
            return item;
        }).collect(Collectors.toList());
        return R.ok(agentStepInfos);
    }
    @Override
    public R merchantCategoryList() {
        List<MerchantCategory> categories = merchantCategoryService.list(Wrappers.<MerchantCategory>lambdaQuery().orderByDesc(MerchantCategory::getSeq));
        Map<String,List<Merchant>>  categoryMap =   merchantService.list(Wrappers.<Merchant>lambdaQuery().select(Merchant::getCategory)).stream().collect(Collectors.groupingBy(Merchant::getCategory));
        categories = categories.stream().map(item -> {
            List<Merchant> merchants = categoryMap.get(item.getCategory());
            if(null != merchants){
                item.setNum(merchants.size());
            } else {
                item.setNum(0);
            }
            return item;
        }).collect(Collectors.toList());
        return R.ok(categories);
    }
    @Override
    public R merchantCategory(MerchantCategory merchant) {
        return R.ok(merchantCategoryService.update(Wrappers.<MerchantCategory>lambdaUpdate().set(MerchantCategory::getSeq,merchant.getSeq()).eq(MerchantCategory::getId,merchant.getId())));
    }
}
